package com.wudizaba.microservicesdemosystem.util;

import com.wudizaba.microservicesdemocommon.constant.ExceptionsConstant;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import java.util.Date;

@Slf4j
public class QuartzUtils {

    // 创建定时任务一部到位
    public static Date createJobAndTrigger(Class<? extends Job> jobClass, String jobName, String jobGroup, String triggerName, String triggerGroup, String cron ,Scheduler scheduler) {
        // 任务实例
        JobDetail jobDetail = JobBuilder.newJob(jobClass)
                .withIdentity(jobName,jobGroup)//参数1：任务名，参数2：分组
                .build();

        //cron表达式 每隔一分钟执行一次
        CronScheduleBuilder scheduleBuilder =
                CronScheduleBuilder.cronSchedule(cron);


        // 任务触发器
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerName, triggerGroup)
                .withSchedule(scheduleBuilder)// 使用cron表达式,每隔一分钟执行一次
//                .startNow()// 立即执行
                .build();

        // 手动将触发器与任务绑定到调度器内
        Date date = null;
        try {
            date = scheduler.scheduleJob(jobDetail, trigger);
            // 启动调度器
            scheduler.start();
        } catch (SchedulerException e) {
//            throw new QuartzException(ExceptionsConstant.QUARTZ_JOB_NOT_RUNNING);
            log.error(ExceptionsConstant.QUARTZ_JOB_NOT_RUNNING, e);
        }



        return date;

    }


}